package com.simplehire.controller;

import com.simplehire.model.User;
import com.simplehire.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/register")
    public String showRegistrationForm() {
        return "register";
    }

    @PostMapping("/register")
    public String registerUser(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam(required = false) String confirmPassword,
            Model model) {

        // 1. 验证表单数据
        if (username == null || username.trim().isEmpty()) {
            model.addAttribute("error", "用户名不能为空");
            return "register";
        }

        if (username.length() < 4 || username.length() > 20) {
            model.addAttribute("error", "用户名长度必须在4-20个字符之间");
            return "register";
        }

        // 2. 检查用户名是否已存在
        if (userRepository.existsByUsername(username)) {
            model.addAttribute("error", "用户名已被占用，请选择其他用户名");
            return "register";
        }

        // 3. 验证密码
        if (password == null || password.length() < 6) {
            model.addAttribute("error", "密码长度不能少于6位");
            return "register";
        }

        if (confirmPassword == null || !confirmPassword.equals(password)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";
        }

        // 4. 创建并保存用户
        User user = new User();
        user.setUsername(username);
        user.setPassword(passwordEncoder.encode(password));
        userRepository.save(user);

        return "redirect:/login?success=注册成功，请登录";
    }

    @GetMapping("/login")
    public String showLoginForm(Model model, @RequestParam(required = false) String success) {
        if (success != null) {
            model.addAttribute("success", success);
        }
        return "login";
    }
}
